﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using System.Web.Script.Serialization;

using Fuse8.DomainFramework.BusinessService;

using Fuse8.ContentManagementFramework.Domain.Special;
using Fuse8.ContentManagementFramework.SystemFacade.Extensions;

namespace Fuse8.ContentManagementFramework.Domain
{
    public partial class CmsTemplate
    {
        private IEnumerable<CmsTemplateRegion> _templateRegions;
        private int _templateRegionsCount;

        public CmsTemplateTypeKind TemplateType
        {
            get
            {
                return (CmsTemplateTypeKind)Enum.ToObject(typeof(CmsTemplateTypeKind), TemplateTypeKey);
            }
        }

        public string TemplateTypeDescription
        {
            get
            {
                return TemplateType.GetDescription();
            }
        }

        public int TemplateRegionsCount 
        { 
            get
            {
                if (_templateRegionsCount == 0)
                { 
                    _templateRegionsCount = _templateRegions != null ?
                        _templateRegions.Count() :
                        0;
                }

                return _templateRegionsCount;
            }
            set
            {
                if (value >= 0)
                {
                    _templateRegionsCount = value;
                }
            }
        }

        [XmlIgnore]
        [ScriptIgnore]
        public bool HasRegions
        {
            get
            {
                return _templateRegions != null;
            }
        }
        
        [XmlIgnore]
        [ScriptIgnore]        
        public IEnumerable<CmsTemplateRegion> TemplateRegions
        {
            //note: it is needed to call ToList() here to safely put _templateregions to cache or StateServer session
            get
            {
                if (_templateRegions == null)
                {
                    var businessFacade = new BusinessServiceFacade<CmsTemplateRegion, int>();                    
                    _templateRegions = businessFacade.FindAll().Where(p => p.TemplateId == Id).ToList();
                    
                }

                return _templateRegions;
            }
            set
            {
                if (value != null)
                {
                    _templateRegions = value.ToList();
                }
            }
        }
    }
}
